//
//  DetaiViewModel.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/23.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import Foundation
import CoreBluetooth

protocol PhotosDetaiViewModelDelegate: AnyObject {
    //刷新
    func refresh(isEnd:Bool)
}
@available(iOS 12.0, *)
class PhotosDetaiViewModel: BaseViewModel {
    
    //倒计时Timer
    private var countdownTimer: Timer?
    private var remainingTime: Int = 3 //单位：秒
    private var totalTime: Int = 3
    
    //蓝牙管理
    private let bluetoothManager = BluetoothManagerTool.shared
    
    //wifi管理
    private var isYehuo:Bool = false
    private var isSFTP:Bool = false


    private var tcpConnection: TCPConnection?
    private var sftpManager = SFTPManager()
    
    
    weak var delegate: PhotosDetaiViewModelDelegate?
    var onStateUpdate: ((ConectState) -> Void)?
    var deviceModel:DeviceModel? //所选设备
    var screen:Screen? //所选屏幕尺寸
    var photoList = Array<PhotoInforModel>() //  展示的图片数组
    var listPhotosInfosRemote = Array<PhotoInforModel>() //  获取列表的图片数组  这个列表跟上面的不同之处是，它是获取设备下图片的原来列表，用来跟上面的做对比
  
    
    //存储添加的图片临时
    var tempPhotoArray:Array<PhotoInforModel>?;
    var listPhotosCommit = Array<PhotoInforModel>() // 待提交的数据
    var optType:OptionTypeEnum? //功能类型
    var optSubType: OptionTypeEnum.OPE_TYPE_SEND_MULTYPHOTO_SUB?
    var MultiImageIndex = 0 //待更新位号
    let MAXPHOTOS = 50
    /*
     *  发送命令的Data数组
     */
    var buffArr = [UInt8]();
    /*
     * 获取图片列表所需要的数据
     */
    var readImageCnt = 0 //当前读取图片序号
    var buffImage = [UInt8]() //图片数据 包含了 前四位 的图片大小
    var readDataIndexByte = 0  //读取到图片的第几个字节
    var buffImageSize = 0 //当前图片的字节大小
    
    init(delegate: PhotosDetaiViewModelDelegate? = nil, deviceModel: DeviceModel? = nil, screen: Screen? = nil) {
        super.init()
        self.delegate = delegate
        self.deviceModel = deviceModel
        self.screen = screen
        switch screen?.screenType {
        case .ELECTRONICALBUM_2530_BW:fallthrough
        case .ELECTRONICALBUM_2530_E6:fallthrough
        case .ELECTRONICALBUM_2800_E6:fallthrough
        case .ELECTRONICALBUM_3120_BW:fallthrough
        case .ELECTRONICALBUM_4200_BW:
            self.isYehuo = true
        default:
            self.isYehuo = false
        }
        if userManger.curUserInfo?.transmissionMode == 0 {
            setupBluetooth()
        }
    }
     /*
      *获取数据列表
      */
    func getAlubum(){
        optType = .OPE_TYPE_GET_ALL_PHOTO
        self.photoList.removeAll()
        listPhotosInfosRemote.removeAll();
        self.delegate?.refresh(isEnd: false)
        readImageCnt = 0
        readDataIndexByte = 0
        resetBuffImage()
        LoadingManager.shared.showLoading(title:"uploadImageTip1".localized)
        initSendData()
    }
    /*
     * 提交数据列表
     */
    func updateDevicePhotos(){
        LoadingManager.shared.showLoading(title:"uploadImageTip2".localized)
        makeCommitList() //处理待更新的列表
        if(listPhotosCommit.count > 0 ){
            MultiImageIndex = 0
            optType = .OPE_TYPE_SEND_MULTYPHOTO
            initSendData()
        }
    }
    //待更新列表处理
    func makeCommitList(){
        listPhotosCommit.removeAll()
        //add deleteList
        for var remote in listPhotosInfosRemote
        {
            var found = false
            for  org in photoList {
                if remote.imageNo_remote  == org.imageNo_remote {
                    found = true
                    break
                }
            }
            if found == false {
                remote.imageNo_new = 0xff
                listPhotosCommit.append(remote)
            }
         }
          
        //add changlist and addlist
        for (index,var item) in photoList.enumerated() {
            item.imageNo_new = index
            photoList[index].imageNo_new = index
        }

        for item in photoList {
            //新增的数据
            if item.imageNo_remote == 0xff {
                listPhotosCommit.append(item)
            }else if(item.orgImage != nil){
                listPhotosCommit.append(item)
            }else if(item.imageNo_remote != item.imageNo_new){
                listPhotosCommit.append(item)
            }
        }
    }
    //处理单条数据
    func makeImageBuff(index:Int){
        //判断是删除
        if listPhotosCommit[index].imageNo_new == 0xff {
            switch screen?.screenType {
            case .ELECTRONICALBUM_2530_BW:fallthrough
            case .ELECTRONICALBUM_2530_E6:fallthrough
            case .ELECTRONICALBUM_2800_E6:fallthrough
            case .ELECTRONICALBUM_3120_BW:fallthrough
            case .ELECTRONICALBUM_4200_BW:
                //这几款要用野火的驱动板，只能用野火wifi，SFTP
                self.isSFTP = true
                optSubType = .OPE_TYPE_SEND_MULTYPHOTO_SUB_DELETE(listPhotosCommit[index])
            default:
                buffArr = [UInt8].init(repeating: 0, count: 2)
                buffArr[0] = UInt8(CMDEnum.CMD_DEL_BY_NO)
                buffArr[1] = UInt8(listPhotosCommit[index].imageNo_remote ?? 0)
                break
            }
            return
        }
        //修改图片序号
        if listPhotosCommit[index].orgImage == nil {
            switch screen?.screenType {
            case .ELECTRONICALBUM_2530_BW:fallthrough
            case .ELECTRONICALBUM_2530_E6:fallthrough
            case .ELECTRONICALBUM_2800_E6:fallthrough
            case .ELECTRONICALBUM_3120_BW:fallthrough
            case .ELECTRONICALBUM_4200_BW:
                //这几款要用野火的驱动板，只能用野火wifi，SFTP
                self.isSFTP = true
                optSubType = .OPE_TYPE_SEND_MULTYPHOTO_SUB_CHANGE(listPhotosCommit[index])

            default:
                buffArr = [UInt8].init(repeating: 0, count: 3)
                buffArr[0] = UInt8(CMDEnum.CMD_CHGNAME_BY_NO)
                buffArr[1] = UInt8(listPhotosCommit[index].imageNo_remote ?? 0)
                buffArr[2] = UInt8(listPhotosCommit[index].imageNo_new ?? 0)
                break
            }
            return
        }
        //添加图片
        
            
            
            let abgrValues  =  getIntPixelData(from: listPhotosCommit[index].image!)
            let cgimage = listPhotosCommit[index].image!.cgImage
            let width =  cgimage!.width
            let height =  cgimage!.height
        
            switch screen?.screenType {
            case .ELECTRONICALBUM_2530_BW:fallthrough
            case .ELECTRONICALBUM_2530_E6:fallthrough
            case .ELECTRONICALBUM_2800_E6:fallthrough
            case .ELECTRONICALBUM_3120_BW:fallthrough
            case .ELECTRONICALBUM_4200_BW:
                //这几款要用野火的驱动板，只能用野火wifi，SFTP
                isSFTP = true
                optSubType = .OPE_TYPE_SEND_MULTYPHOTO_SUB_ADD(listPhotosCommit[index])
            case .ELECTRONICALBUM_0390_BW:
                let byteLen = width * height * 4 / 8
                buffArr = [UInt8].init(repeating: 0, count: 2 + byteLen)
                buffArr[0] = UInt8(CMDEnum.CMD_ADD_PHOTO_BY_NO)
                buffArr[1] = UInt8(listPhotosCommit[index].imageNo_new ?? 0)
                for index in 0..<byteLen {
                    buffArr[2 + index] = getOneByteWithBW16_uint32(pix1: abgrValues![index*2], pix2: abgrValues![index*2 + 1])
                }
                
            case .ELECTRONICALBUM_1330_E6:fallthrough
            case .ELECTRONICALBUM_3150_E6:
                let byteLen = width * height * 4 / 8
                buffArr = [UInt8].init(repeating: 0, count: 2 + byteLen)
                buffArr[0] = UInt8(CMDEnum.CMD_ADD_PHOTO_BY_NO)
                buffArr[1] = UInt8(listPhotosCommit[index].imageNo_new ?? 0)
                for index in 0..<byteLen {
                    buffArr[2 + index] = getOneByteWithE6_uint32(pix1: abgrValues![index*2], pix2: abgrValues![index*2 + 1])
                }
            case .ELECTRONICALBUM_1160_E5:fallthrough
            case .ELECTRONICALBUM_0970_E5:
                let byteLen = width * height * 2 / 8
                buffArr = [UInt8].init(repeating: 0, count: 2 + byteLen)
                buffArr[0] = UInt8(CMDEnum.CMD_ADD_PHOTO_BY_NO)
                buffArr[1] = UInt8(listPhotosCommit[index].imageNo_new ?? 0)
                for index in 0..<byteLen {
                    buffArr[2 + index] = getOneByteWithE5_uint32(pix1: abgrValues![index*4], pix2: abgrValues![index*4 + 1], pix3: abgrValues![index*4 + 2], pix4: abgrValues![index*4 + 3])
                }
                
            default:
                
                let byteLen = width * height * 4 / 8
                buffArr = [UInt8].init(repeating: 0, count: 2 + byteLen)
                buffArr[0] = UInt8(CMDEnum.CMD_ADD_PHOTO_BY_NO)
                buffArr[1] = UInt8(listPhotosCommit[index].imageNo_new ?? 0)
                for index in 0..<byteLen/2 {
                    buffArr[2 + index] = getOneByteFor7C(pix1: abgrValues![index*4], pix2: abgrValues![index*4 + 1], pix3: abgrValues![index*4 + 2], pix4: abgrValues![index*4 + 3], isP1: true)
                }
                for index in 0..<byteLen/2 {
                    buffArr[2 + byteLen/2 + index] = getOneByteFor7C(pix1: abgrValues![index*4], pix2: abgrValues![index*4 + 1], pix3: abgrValues![index*4 + 2], pix4: abgrValues![index*4 + 3], isP1: false)
                }
                break
            }
    }
    /*
     * 设置指定图片
     */
    func updatePhotos(index:Int){
        optType = .OPE_TYPE_UPDATE_PHOTO
        initSendData(index)
    }
    /*
     * 删除指定图片
     */
    func removePhoto(index:Int){
        self.photoList.remove(at: index)
        self.delegate?.refresh(isEnd: true)
    }
    /*
     * 上一张
     */
    func updatePrevPhoto(){
        optType = .OPE_TYPE_UPDATE_PREV
        initSendData()
    }
    /*
     * 下一张
     */
    func updateNextPhoto(){
        optType = .OPE_TYPE_UPDATE_NEXT
        initSendData()
    }
    /*
     * 开始循环
     */
    func slideOn(repeatInfo:ReapetInfo){
        optType = .OPE_TYPE_UPDATE_REPEAT
        initSendData(reapetInfo:repeatInfo)
    }
    /*
     * 结束循环
     */
    func slideOff(){
        optType = .OPE_TYPE_UPDATE_REPEAT_STOP
        initSendData()
    }
    /*
     * 清空列表
     */
    func clearPhoto(){
        optType = .OPE_TYPE_CLEAR_PHOTO
        self.photoList.removeAll()
        self.listPhotosInfosRemote.removeAll()
        
        self.delegate?.refresh(isEnd: true)
        self.initSendData()
    }
    //重置buff数据
    func resetBuffImage() {
        buffImage = [UInt8](repeating: 0, count: 4 + screen!.allBytes)
        buffImageSize = screen!.allBytes;
    }
    //设置要发送的数据
    func initSendData(_ settingIndex:Int? = nil,reapetInfo:ReapetInfo? = nil) {
        isSFTP = false
        switch optType {
        case .OPE_TYPE_GET_ALL_PHOTO:
            if isYehuo {
                isSFTP = true
            }else{
                buffArr = [UInt8].init(repeating: 0, count: 2)
                buffArr[0] = UInt8(CMDEnum.CMD_VIEW_BY_NO)
                buffArr[1] = UInt8(readImageCnt)
                readImageCnt += 1
            }
        case .OPE_TYPE_SEND_MULTYPHOTO:
            makeImageBuff(index:MultiImageIndex )
            MultiImageIndex += 1
        case .OPE_TYPE_UPDATE_PHOTO:
            buffArr = [UInt8].init(repeating: 0, count: 2)
            buffArr[0] = UInt8(CMDEnum.CMD_UPDATE_BY_NO)
            buffArr[1] = UInt8(settingIndex ?? 0)
        case .OPE_TYPE_UPDATE_NEXT:
            buffArr = [UInt8].init(repeating: 0, count: 1)
            buffArr[0] = UInt8(CMDEnum.CMD_NEXT)
        case .OPE_TYPE_UPDATE_PREV:
            buffArr = [UInt8].init(repeating: 0, count: 1)
            buffArr[0] = UInt8(CMDEnum.CMD_PREV)
        case .OPE_TYPE_CLEAR_PHOTO:
            if isYehuo {
                isSFTP = true
            }else{
                buffArr = [UInt8].init(repeating: 0, count: 2)
                buffArr[0] = UInt8(CMDEnum.CMD_DEL_BY_NO)
                buffArr[1] = UInt8(CMDEnum.CMD_CLEARNO)
            }
        case .OPE_TYPE_UPDATE_REPEAT:
            buffArr = [UInt8].init(repeating: 0, count: 5)
            buffArr[0] = UInt8(CMDEnum.CMD_SLIDE_ON)
            //设置时
            buffArr[1] = UInt8((reapetInfo?.hour ?? 0) / 256); // wait times high
            buffArr[2] = UInt8((reapetInfo?.hour ?? 0) % 256); // wait times low
            //设置分
            buffArr[3] = UInt8 ((reapetInfo?.minute ?? 0) % 256); // wait times low
            //设置秒
            buffArr[4] = UInt8 ((reapetInfo?.second ?? 0) % 256); // wait times low
        case .OPE_TYPE_UPDATE_REPEAT_STOP:
            buffArr = [UInt8].init(repeating: 0, count: 1)
            buffArr[0] = UInt8(CMDEnum.CMD_SLIDE_OFF)
        default: break
        }
        if userManger.curUserInfo?.transmissionMode == 0 {
            connectToBlue()
        }else{
            if isSFTP {
               demonstrateSFTP()
            }else{
                //TCP协议
               demonstrateTCP()
            }
        }
    }
}
//通用函数处理
@available(iOS 12.0, *)
extension PhotosDetaiViewModel{
    //状态监听
    func onstates(state:ConectState){
        
        self.onStateUpdate?(state)
         switch state {
         case .unknown:
             LoadingManager.shared.hideLoading()
             break
         case .resetting:break
         case .unsupported:
             LoadingManager.shared.hideLoading()
             break
         case .unauthorized:
             LoadingManager.shared.hideLoading()
             break
         case .poweredOff:
             LoadingManager.shared.hideLoading()
             break //关闭
         case .poweredOn:
             LoadingManager.shared.hideLoading()
             break//蓝牙开启
         case .scanning:break //扫描中
         case .stopScan:
             break  //停止扫描 结束判断设备是否在周围
         case .noFountDevice:
             LoadingManager.shared.hideLoading()
             break //未发现设备
         case .noConnectDevice:
             LoadingManager.shared.hideLoading()
             bluetoothManager.disconnect()
             break
         case .connecting:
             break //正在连接
         case .connected:
             break  //已连接
         case .disconnecting:break //正在断开连接
         case .disconnected:
             LoadingManager.shared.hideLoading()
             break //连接已断开
         case .serviceDiscovering:break //正在发现服务
         case .characteristicDiscovering:break //正在发现特征
         case .ready:
             sendData()
             break //已准备好，可发送消息
         case .complate:
             LoadingManager.shared.hideLoading()
             break
         case.error(let str):
             LoadingManager.shared.hideLoading()
         default: break
         }
    }
    func sendData(){
        var isGetAll = false
        switch optType {
        case .OPE_TYPE_GET_ALL_PHOTO:
            isGetAll = true
        case .OPE_TYPE_SEND_MULTYPHOTO: LoadingManager.shared.updateLoadingTitle(("uploadPhotoStart".localized + String(describing: "\(self.MultiImageIndex)") + "uploadEnd".localized))
        case .OPE_TYPE_UPDATE_PHOTO:break
        case .OPE_TYPE_UPDATE_NEXT: break
        case .OPE_TYPE_UPDATE_PREV: break
        case .OPE_TYPE_CLEAR_PHOTO: break
        case .OPE_TYPE_UPDATE_REPEAT: break
        case .OPE_TYPE_UPDATE_REPEAT_STOP: break
        default: break
        }
        
        if userManger.curUserInfo?.transmissionMode == 0 {
            _  = bluetoothManager.sendData(Data(bytes: buffArr), isGetPhotos: isGetAll)
            return
        }else{
            if isSFTP {
                
            }else{
                tcpConnection?.sendData(Data(bytes: buffArr),optType: optType!)
            }
        }
    }
}
/*
 *蓝牙处理
 */
@available(iOS 12.0, *)
extension PhotosDetaiViewModel{
    private func setupBluetooth() {
        bluetoothManager.dataReceiver = self
        bluetoothManager.onStateUpdate = { [weak self] state in
            self?.onstates(state: state)
        }
    }
    //获取蓝牙对象
    func getPer() -> CBPeripheral?{
        let peripheral:CBPeripheral?
        if self.deviceModel?.per == nil
        {
            peripheral =  BluetoothManagerTool.shared.getPeripheralWithUUid(uuid: self.deviceModel?.ID ?? "")
            self.deviceModel?.per = peripheral
            
        }else{
            peripheral = self.deviceModel?.per
        }
        return peripheral
    }
    //连接蓝牙设备
    func connectToBlue(){
        let peripheral = getPer()
        if(peripheral == nil){
            appManger.getCurrentUIVC().view.showToastCenter(message: "获取设备出现错误")
            return
        }
        self.bluetoothManager.connect(to:self.deviceModel!)
    }
    
    func closeBlu(){
        bluetoothManager.disconnect()
    }
}
/*
 * 蓝牙数据处理回调函数
 */
@available(iOS 12.0, *)
extension PhotosDetaiViewModel:BluetoothDataReceiver{
    // MARK: - BluetoothDataReceiver
    func didReceiveData(_ data: Data, from peripheral: CBPeripheral) {
        receiveData(data: data)
    }
    func didSendData(_ data: Data, to peripheral: CBPeripheral, error: Error?) {
        
        
    }
    //蓝牙处理函数
    func receiveData(data:Data){
        if data.count == 6 {
            //上传图片返回的应答
            let bytes = data.bytes
            if (bytes[0] == 0x00)
                && (bytes[1] == 0x00)
                && (bytes[2] == 0x00)
                && (bytes[3] == 0x02)
                && (bytes[4] == 0x78)
                && (bytes[5] == 0x00)
            {
                if optType == OptionTypeEnum.OPE_TYPE_SEND_MULTYPHOTO {
                    sendNextMutiImage()
                }
               return
            }
            if (bytes[0] == 0x00)
                && (bytes[1] == 0x00)
                && (bytes[2] == 0x00)
                && (bytes[3] == 0x02)
                && (bytes[4] == 0x78)
                && (bytes[5] == 0x01)
            {
                //数据发送失败 重新发送数据
                if optType == OptionTypeEnum.OPE_TYPE_SEND_MULTYPHOTO {
                    AlertManager.shared.showConfirm(title: "tips".localized, message: "confirmTip5".localized,confirmAction:  { [self] in
                        MultiImageIndex -= 1
                        sendNextMutiImage()
                    })
                }
               return
            }
            return
        }
        //接收图片的应答
        recivePhoto(data: data)
    }
    func sendNextMutiImage() {
        if MultiImageIndex < listPhotosCommit.count {
            Thread.sleep(forTimeInterval: 1)
            initSendData()
        }else{
            DebugLog("全部上传完成 \(self.readImageCnt) 张图片")
            self.onstates(state: .complate)
            disConnect()
            AlertManager.shared.showAlert(title: "tips".localized,message: "confirmTip1".localized,buttonAction:  {
                self.getAlubum()
            })
        }
    }
}
/*
 * 接收图片处理
 */
@available(iOS 12.0, *)
extension PhotosDetaiViewModel{
    func recivePhoto(data:Data){
        cancelTimer()
        let bytes = data.bytes
        DebugLog("once recive data bytes = \(bytes.count)" + " readDataIndexByte:\(readDataIndexByte)")
        for oneByte in bytes {
            //判断如果读取的位置超过了 图片的实际大小和4字节的图片大小值
            if readDataIndexByte >= buffImageSize + 4 {
                break
            }
            //buffImage 的前四个字节是图片的大小，后面字节才是图片内容，所以绘制image的时候要记得偏移4个字节
            buffImage[readDataIndexByte] = oneByte
            //读取下一个字节
            readDataIndexByte+=1
            
            //前四个四节是图片大小
            if readDataIndexByte == 4 {
                //查看实际的图片大小
                var imageSize:Int = 0
                imageSize = (imageSize << 8) + Int(buffImage[0])
                imageSize = (imageSize << 8) + Int(buffImage[1])
                imageSize = (imageSize << 8) + Int(buffImage[2])
                imageSize = (imageSize << 8) + Int(buffImage[3])
                buffImageSize = imageSize
                DebugLog("1 RECV DATA size imageSize = \(buffImageSize)")
                if buffImageSize > 0 {
                    LoadingManager.shared.updateLoadingTitle(("getPhotoStart".localized + String(describing: "\(self.readImageCnt)") + "getPhotoEnd".localized))
                }
                switch screen?.screenType {
                case .ELECTRONICALBUM_0390_BW:
                    if buffImageSize >= screen!.allBytes {
                        buffImageSize = screen!.allBytes
                    }
                case .ELECTRONICALBUM_0750_E5:
                    if buffImageSize >= screen!.allBytes {
                        buffImageSize = screen!.allBytes
                    }else if(buffImageSize > 48000){
                        buffImageSize = 48000
                    }else if(buffImageSize > 12000){
                        buffImageSize = 12000
                    }
                default:
                    break;
                }
            }
        }
        if buffImageSize != 0 && readDataIndexByte >= buffImageSize {
            // 一张图片获取完成
            DebugLog("获取完一张图片 = \(buffImageSize)")
            //处理图片
            showReadAlbumImage(buffImageSize)
            // 获取下一张图片
            requestNextPhotos()
        }else if(readDataIndexByte >= 4 && buffImageSize == 0){
           //全部图片获取完成
            DebugLog("全部图片获取完成 \(self.readImageCnt - 1) 张图片")
            self.onstates(state: .complate)
            appManger.getCurrentUIVC().view.showToastCenter(message: "photo_tip6".localized)
            disConnect()
        }else{
            startTimer()
        }
    }
    func requestNextPhotos() {
        if readImageCnt < MAXPHOTOS {
            readDataIndexByte = 0
            resetBuffImage()
            initSendData()
        }
    }
    func showReadAlbumImage(_ imageSize:Int){
        //判断图片是否被缩放
        if imageSize == screen!.allBytes {
            showAlbumImage(imageData:buffImage, width: screen!.width, height: screen!.height)
            
        }else if(imageSize == screen!.allBytes/4){
            showAlbumImage(imageData:buffImage, width: screen!.width/2, height: screen!.height/2)
        }
        else if(imageSize == screen!.allBytes/16){
            showAlbumImage(imageData:buffImage, width: screen!.width/4, height: screen!.height/4)
        }
    }
    func showAlbumImage(imageData:[UInt8],width:Int,height:Int) {
 
        //imageData中，每个像素占用4个Bit，如果转换图片，需要转换成标准的ARGB像素点  每个点的4 位转换为每个点的32位值
        var pixelsN = [UInt32](repeating: 0, count: width * height)
        
        switch screen?.screenType {
        case .ELECTRONICALBUM_0390_BW:
            //实际要转换的数据总字节数 ,抖动后的数据，一个像素占用4Bit，
            let totalByte = width * height * 4/8
            //拿字节
            for index in 0..<totalByte {
                //每个字节8位包含两个像素点
                for j in 0...1 {
                    let colorType = PixUtils.getArgbColorType_BW16_WithByte(byte: imageData[4 + index], pix: j)
                    pixelsN[index*2 + j] = colorType
                }
            }
        case .ELECTRONICALBUM_0750_E5:
            let totalByte = width * height * 2/8
            //拿字节
            for index in 0..<totalByte {
                //每个字节8位包含两个像素点
                for j in 0...3 {
                    let color = PixUtils.getArgbColorType_7color_WithByte(byte0: imageData[4 + index], byte1: imageData[4 + index + totalByte], pix: j)
                    pixelsN[index*4 + j] =  color
                }
            }
            
        case .ELECTRONICALBUM_0970_E5:fallthrough
        case .ELECTRONICALBUM_1160_E5:
            //实际要转换的数据总字节数 ,抖动后的数据，一个像素占用2Bit，  4个颜色，2bit就可以表示
            let totalByte = width * height * 2/8
            //拿字节
            for index in 0..<totalByte {
                //每个字节8位包含四个像素点
                for j in 0...3 {
                    let color = PixUtils.getArgbColorType_E5_WithByte(byte: imageData[4 + index], pix: j)
                    pixelsN[index*2 + j] = color
                }
            }
            
        case .ELECTRONICALBUM_1330_E6:fallthrough
        case .ELECTRONICALBUM_3150_E6:
            //实际要转换的数据总字节数 ,抖动后的数据，一个像素占用4Bit，
            let totalByte = width * height * 4/8
            //拿字节
            for index in 0..<totalByte {
                //每个字节8位包含两个像素点
                for j in 0...1 {
                    let color = PixUtils.getArgbColorType_E6_WithByte(byte: imageData[4 + index], pix: j)
                    pixelsN[index*2 + j] = color
                }
            }
        default:
            break
        }
        let image:UIImage = createImageFromIntColors(pixelsN, width: width, height: height) ?? UIImage()
        let photoModel =  PhotoInforModel(image: image,imageNo_remote: photoList.count,imageNo_new: photoList.count)
        photoList.append(photoModel)
        listPhotosInfosRemote.append(PhotoInforModel(image: image,imageNo_remote: listPhotosInfosRemote.count,imageNo_new: listPhotosInfosRemote.count))
        self.delegate?.refresh(isEnd: false)
    }
}
/*
  *   wifi的处理
  */
@available(iOS 12.0, *)
extension PhotosDetaiViewModel {
    func demonstrateTCP() {
        if tcpConnection == nil {
            // 创建TCP连接
            self.tcpConnection = TCPConnection(isYehuo: isYehuo)
            self.tcpConnection?.delegate = self
            // 连接TCP
            self.tcpConnection?.connect()
        }else{
            switch tcpConnection?.state {
            case .connected:
                self.onstates(state: .ready)
            default:
                self.tcpConnection = TCPConnection(isYehuo: isYehuo)
                self.tcpConnection?.delegate = self
                // 连接TCP
                self.tcpConnection?.connect()
            }
        }
    }
    func demonstrateSFTP() {
        self.onstates(state: .connecting )
        let suc = sftpManager.connect()
        if !suc {
             self.onstates(state: .noConnectDevice)
             return
        }else{
            self.onstates(state: .connected )
        }
        self.onstates(state: .communication)
        switch optType {
        case .OPE_TYPE_GET_ALL_PHOTO:
            LoadingManager.shared.updateLoadingTitle(("getPhotoStart".localized + String(describing: "\(1)") + "getPhotoEnd".localized))
           
            DispatchQueue.global(qos: .background).async { [self] in
                self.getAllPhoto()
            }
        case .OPE_TYPE_SEND_MULTYPHOTO:
            LoadingManager.shared.updateLoadingTitle(("uploadPhotoStart".localized + String(describing: "\(self.MultiImageIndex)") + "uploadEnd".localized))
            switch optSubType {
            case .OPE_TYPE_SEND_MULTYPHOTO_SUB_DELETE(let photoInfo):do {
                DispatchQueue.global(qos: .background).async { [self] in
                    let suc = sftpManager.deleteFile(index: photoInfo.imageNo_remote ?? 0)
                    DispatchQueue.main.async {
                        if suc {
                            self.sendNextMutiImage()
                        }else{
                            AlertManager.shared.showConfirm(title: "tips".localized, message: "confirmTip5".localized,confirmAction:  { [self] in
                                MultiImageIndex -= 1
                                sendNextMutiImage()
                            })
                        }
                    }
                }
            }
            case .OPE_TYPE_SEND_MULTYPHOTO_SUB_CHANGE(let photoInfo):do {
                DispatchQueue.global(qos: .background).async { [self] in
                    let suc = sftpManager.renameItem(oldIndex: photoInfo.imageNo_remote!, to: photoInfo.imageNo_new!)
                    DispatchQueue.main.async {
                        if suc {
                            self.sendNextMutiImage()
                        }else{
                            AlertManager.shared.showConfirm(title: "tips".localized, message: "confirmTip5".localized,confirmAction:  { [self] in
                                MultiImageIndex -= 1
                                sendNextMutiImage()
                            })
                        }
                    }
                }
            }
            case .OPE_TYPE_SEND_MULTYPHOTO_SUB_ADD(let photoInfo):do {
                DispatchQueue.global(qos: .background).async { [self] in
                    let suc = sftpManager.uploadFile(photoInfo:photoInfo ,index: photoInfo.imageNo_new!)
                    DispatchQueue.main.async {
                        if suc {
                            self.sendNextMutiImage()
                        }else{
                            AlertManager.shared.showConfirm(title: "tips".localized, message: "confirmTip5".localized,confirmAction:  { [self] in
                                MultiImageIndex -= 1
                                sendNextMutiImage()
                            })
                        }
                    }
                }
            }
                
            default:
                break
            }
        case .OPE_TYPE_CLEAR_PHOTO:
            DispatchQueue.global(qos: .background).async { [self] in
                _ = sftpManager.deleteAll()
                DispatchQueue.main.async { [self] in
                    appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip4".localized)
                    self.onstates(state: .complate)
                    self.disConnect()
                }
            }
        default: break
        }
    }

   func getAllPhoto(){
       sftpManager.getAllphotos(complateOneImage: { (totoal,current,image) in
           DispatchQueue.main.async {
               let photoModel =  PhotoInforModel(image: image,imageNo_remote: self.photoList.count,imageNo_new: self.photoList.count)
               self.photoList.append(photoModel)
               self.listPhotosInfosRemote.append(PhotoInforModel(image: image,imageNo_remote: self.listPhotosInfosRemote.count,imageNo_new: self.listPhotosInfosRemote.count))
               self.delegate?.refresh(isEnd: false)
               if current == totoal - 1 {
                   LoadingManager.shared.hideLoading()
                   self.onstates(state: .complate)
                   appManger.getCurrentUIVC().view.showToastCenter(message: "photo_tip6".localized)
                   self.onstates(state: .complate)
                   self.disConnect()
               }else{
                   let index = current + 2
                   LoadingManager.shared.updateLoadingTitle(("getPhotoStart".localized + String(describing: "\(index)") + "getPhotoEnd".localized))
               }
           }
       })
    }
}
//wifi的函数回调以及监听状态
// 实现代理方法
@available(iOS 12.0, *)
extension PhotosDetaiViewModel: DataTransferDelegate {
    func didReceiveData(_ data: Data, from connection: TCPConnection) {
        print("Received data: \(data.count) bytes from connection \(connection.id)")
        // 处理接收到的数据
        if data.count == 6 {
            ackDataWithWifi(data: data)
        }else if(data.count == 8){
            if let string = String(data: data, encoding: .utf8) {
                print(string)
            } else {
                print(data)
            }
        }else{
            recivePhoto(data: data)
        }
    }
    func ackDataWithWifi(data:Data){
        switch optType {
        case .OPE_TYPE_GET_ALL_PHOTO:break
        case .OPE_TYPE_SEND_MULTYPHOTO:
            sendNextMutiImage()
        case .OPE_TYPE_UPDATE_PHOTO:
            appManger.getCurrentUIVC().view.showToastCenter(message: "photo_tip1".localized)
            self.onstates(state: .complate)
            disConnect()
        case .OPE_TYPE_UPDATE_NEXT:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip1".localized)
            self.onstates(state: .complate)
            disConnect()
        case .OPE_TYPE_UPDATE_PREV:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip1".localized)
            self.onstates(state: .complate)
            disConnect()
        case .OPE_TYPE_CLEAR_PHOTO:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip4".localized)
            self.onstates(state: .complate)
            disConnect()
        case .OPE_TYPE_UPDATE_REPEAT:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip2".localized)
            self.onstates(state: .complate)
            disConnect()
        case .OPE_TYPE_UPDATE_REPEAT_STOP:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip3".localized)
            self.onstates(state: .complate)
            disConnect()
        default: break
        }
    }
    func didSendData(_ data: Data, from connection: TCPConnection) {
        print("Sent data: \(data.count) bytes from connection \(connection.id)")
        self.onstates(state: .communication)
        switch optType {
        case .OPE_TYPE_GET_ALL_PHOTO:break
        case .OPE_TYPE_SEND_MULTYPHOTO:break
        case .OPE_TYPE_UPDATE_PHOTO:
            appManger.getCurrentUIVC().view.showToastCenter(message: "photo_tip5".localized)
        case .OPE_TYPE_UPDATE_NEXT:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip5".localized)
        case .OPE_TYPE_UPDATE_PREV:
            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip5".localized)
        case .OPE_TYPE_CLEAR_PHOTO:break
//            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip8".localized)
        case .OPE_TYPE_UPDATE_REPEAT:break
//            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip7".localized)
        case .OPE_TYPE_UPDATE_REPEAT_STOP:break
//            appManger.getCurrentUIVC().view.showToastCenter(message:  "photo_tip7".localized)
        default: break
        }
    }
    func connectionStateDidChange(_ state: NetworkConnectionState, for connection: TCPConnection) {
       
        DispatchQueue.main.async {
            switch state {
            case .connected:
                self.onstates(state: .connected)
                // 设置扫描超时
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
                    self?.onstates(state: .ready)
                }
                print("TCP已连接，可发送数据")
            case .disconnected:
                self.onstates(state: .disconnected)
                print("TCP连接已断开")
            case .connecting:
                self.onstates(state: .connecting)
                print("正在连接TCP...")
            case .error(let error):
                self.onstates(state: .error(error.localizedDescription))
                print("TCP连接错误: \(error.localizedDescription)")
            }
        }
    }
    func disConnect() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
            if userManger.curUserInfo?.transmissionMode == 0 {
                return
            }else{
                if self!.isSFTP {
                    self?.sftpManager.disconnect()
                }else{
                    self?.tcpConnection?.disconnect()
                }
            }
        }
    }
}
/*
  *   图片抖动处理
  */
@available(iOS 12.0, *)
extension PhotosDetaiViewModel{
   
    func addPhotosWithImages(photoArray:[PhotoInforModel]){
        tempPhotoArray = photoArray
        LoadingManager.shared.showLoading(title:"uploadImageTip2".localized)
        openTak(index: 0)
    }
    func openTak(index:Int) {
        var photoInfo = tempPhotoArray?[index]
        DispatchQueue.global(qos: .background).async { [self] in
              getProcessedImage(photoInfo: photoInfo!, screen: screen!) { image in
                  // 在这里执行耗时操作
                  photoInfo?.image = image;
                  photoInfo?.imageNo_new = photoList.count
                  // 任务完成后回到主线程更新UI
                  DispatchQueue.main.async { [self] in
                      photoList.append(photoInfo!)
                      let newIndex = index + 1
                      if newIndex < tempPhotoArray!.count{
                          self.delegate?.refresh(isEnd: false)
                          openTak(index: newIndex)
                      }else{  
                          self.delegate?.refresh(isEnd: true)
                          LoadingManager.shared.hideLoading {[weak self] in
                              self?.imageparsingcompleted()
                          }
                    }
                }
            }
        }
    }
    
    func imageparsingcompleted(){
        AlertManager.shared.showConfirm(title: "tips".localized, message: "uploadImageTip3".localized,confirmAction:  { [self] in
            self.updateDevicePhotos()
        })
    }
}
@available(iOS 12.0, *)
extension PhotosDetaiViewModel{
    // MARK: - Timer Methods
    private func startTimer() {
        countdownTimer?.invalidate() // 确保之前的计时器已停止
        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            
            self.remainingTime -= 1
            if self.remainingTime <= 0 {
                self.countdownTimer?.invalidate()
                self.countdownFinished()
            }
        }
    }
     private func cancelTimer() {
            countdownTimer?.invalidate()
            remainingTime = totalTime
    }
    private func countdownFinished() {
        // 计时完成后的处理
        remainingTime = totalTime
        AlertManager.shared.showConfirm(title: "tips".localized, message: "confirmTip3".localized,confirmAction:  { [self] in
                self.readImageCnt -= 1;
                self.requestNextPhotos()
        }) {
            LoadingManager.shared.hideLoading()
        }
        // 添加震动反馈
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)
    }
}
